﻿using Microsoft.Extensions.Configuration;
using MongoDB.Bson;
using MongoDB.Driver;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Common.Mongodb
{
    public class MongodbHelp<T>
    {
        private string _collName;
        private readonly IConfiguration _configuration;
        public IMongoClient _mongoClient { get; private set; }
        public IMongoDatabase _mongoDb { get; private set; }

        public MongodbHelp(IConfiguration configuration)
        {
            _configuration = configuration;
            Init();
        }

        public void Init(string connStr = null, string dbName = null, string collName = null)
        {
            if (_mongoClient == null)
                _mongoClient = new MongoClient(connStr ?? _configuration["Mongodb:connStr"]);
            if (_mongoDb == null)
                _mongoDb = _mongoClient.GetDatabase(dbName ?? _configuration["Mongodb:dbName"]);
            if (!string.IsNullOrWhiteSpace(collName))
                _collName = collName;
            else
                _collName = _configuration["Mongodb:dbName"];
        }

        public void InsertAsync(T obj)
        {
            var collention = _mongoDb.GetCollection<T>(_collName);
            collention.InsertOneAsync(obj);
        }

        public void InsertAsync(Dictionary<string, object> keyValues)
        {
            var collention = _mongoDb.GetCollection<BsonDocument>(_collName);
            var doc = new BsonDocument(keyValues);
            collention.InsertOneAsync(doc);
        }

        public void InsertAsync(string collName, T obj)
        {
            var collention = _mongoDb.GetCollection<T>(collName);
            collention.InsertOneAsync(obj);
        }

        public void InsertAsync(string collName, Dictionary<string, object> keyValues)
        {
            var collention = _mongoDb.GetCollection<BsonDocument>(collName);
            var doc = new BsonDocument(keyValues);
            collention.InsertOneAsync(doc);
        }
    }
}
